<template>
  <div class="hotel-detail-container">
    <!-- 酒店信息卡片 -->
    <el-card class="hotel-info-card">
      <template #header>
        <div class="card-header">
          <h2>{{ hotel.hotelName }}</h2>
          <el-rate v-model="hotel.rating" disabled show-score text-color="#ff9900" />
        </div>
      </template>
      
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      
      <div v-else class="hotel-content">
        <div class="hotel-image">
          <img :src="hotel.image || '/src/assets/default.png'" alt="酒店图片">
        </div>
        
        <div class="hotel-details">
          <div class="detail-item">
            <el-icon><Location /></el-icon>
            <span>{{ hotel.country }} {{ hotel.city }}</span>
          </div>
          <div class="detail-item">
            <el-icon><InfoFilled /></el-icon>
            <span>{{ hotel.description || '暂无描述' }}</span>
          </div>
          <div class="detail-item">
            <el-icon><Phone /></el-icon>
            <span>{{ hotel.phone || '暂无联系方式' }}</span>
          </div>
          <div class="detail-item">
            <el-icon><House /></el-icon>
            <span>房间数量: {{ hotel.roomCount || '未知' }}</span>
          </div>
        </div>
      </div>
    </el-card>
    
    <!-- 酒店位置地图 -->
    <el-card class="hotel-map-card">
      <template #header>
        <div class="card-header">
          <h2>酒店位置</h2>
        </div>
      </template>
      
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="3" animated />
      </div>
      
      <div v-else-if="!hotel.longitude || !hotel.latitude" class="empty-container">
        <el-empty description="暂无位置信息" />
      </div>
      
      <div v-else class="map-container">
        <a-map-component :single-hotel="hotel" height="400px" />
      </div>
    </el-card>
    
    <!-- 房间列表卡片 -->
    <el-card class="hotel-rooms-card">
      <template #header>
        <div class="card-header">
          <h2>酒店房间</h2>
          <span>{{ rooms.length }}种房型</span>
        </div>
      </template>
      
      <div v-if="roomsLoading" class="loading-container">
        <el-skeleton :rows="3" animated />
      </div>
      
      <div v-else-if="roomsError" class="empty-container">
        <el-empty description="房间加载失败，请稍后再试">
          <template #extra>
            <el-button type="primary" @click="fetchRooms">重新加载</el-button>
          </template>
        </el-empty>
      </div>
      
      <div v-else-if="rooms.length === 0" class="empty-container">
        <el-empty description="暂无房间信息" />
      </div>
      
      <div v-else>
        <el-row :gutter="20">
          <el-col :span="24" v-for="room in rooms" :key="room.roomType" class="room-card-col">
            <el-card class="room-card" shadow="hover">
              <div class="room-layout">
                <div class="room-image">
                  <img :src="room.image || '/src/assets/default.png'" alt="房间图片">
                </div>
                <div class="room-info">
                  <h3 class="room-type">{{ room.roomType }}</h3>
                  <div class="room-meta">
                    <div class="room-price">¥ {{ room.price }} <span>/ 晚</span></div>
                    <div class="room-available">剩余: {{ room.availableCount }} 间</div>
                  </div>
                  <div class="room-features">
                    <el-tag size="small" v-if="room.breakfast === '1'" type="success">含早餐</el-tag>
                    <el-tag size="small" v-else>不含早餐</el-tag>
                  </div>
                  <div class="room-actions">
                    <el-button type="primary" @click="createOrder(room)" :disabled="room.availableCount <= 0">
                      预订房间
                    </el-button>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-card>
    
    <!-- 酒店评价卡片 -->
    <el-card class="hotel-reviews-card">
      <template #header>
        <div class="card-header">
          <h2>酒店评价</h2>
          <span>{{ reviews.length }}条评价</span>
        </div>
      </template>
      
      <div v-if="reviewsLoading" class="loading-container">
        <el-skeleton :rows="3" animated />
      </div>
      
      <div v-else-if="reviewsError" class="empty-container">
        <el-empty description="评论加载失败，请稍后再试">
          <template #extra>
            <el-button type="primary" @click="retryLoadReviews">重新加载</el-button>
          </template>
        </el-empty>
      </div>
      
      <div v-else-if="reviews.length === 0" class="empty-container">
        <el-empty description="暂无评价" />
      </div>
      
      <div v-else class="reviews-list">
        <el-timeline>
          <el-timeline-item
            v-for="review in reviews"
            :key="review.reviewId"
            :timestamp="formatDate(review.reviewTime)"
            placement="top"
          >
            <el-card class="review-card">
              <div class="review-header">
                <span class="user-id">用户ID: {{ review.userId }}</span>
                <el-rate v-model="review.rating" disabled show-score text-color="#ff9900" />
              </div>
              <div class="review-content">
                {{ review.content }}
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-card>
    
    <div class="action-buttons">
      <el-button type="primary" @click="goBack">返回</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getHotelByName } from '@/api/hotel'
import { getReviewsByHotel } from '@/api/review'
import { getRoomsByHotel } from '@/api/room'
import { Location, InfoFilled, Phone, House } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import AMapComponent from '@/components/AMapComponent.vue'

interface Hotel {
  hotelName: string;
  image?: string;
  country?: string;
  city?: string;
  description?: string;
  phone?: string;
  roomCount?: number;
  rating?: number;
  longitude?: string | number;
  latitude?: string | number;
}

interface Review {
  reviewId: number;
  userId: string;
  hotelName: string;
  rating: number;
  content: string;
  reviewTime: string;
}

interface Room {
  roomType: string;
  hotelName: string;
  price: number;
  availableCount: number;
  breakfast: string;
  image?: string;
}

const route = useRoute()
const router = useRouter()
const hotel = ref<Hotel>({
  hotelName: '',
  rating: 0
})
const reviews = ref<Review[]>([])
const rooms = ref<Room[]>([])
const loading = ref(true)
const reviewsLoading = ref(true)
const reviewsError = ref(false)
const roomsLoading = ref(true)
const roomsError = ref(false)

// 获取酒店详情
const fetchHotelDetail = async () => {
  const hotelName = route.params.hotelName as string
  if (!hotelName) {
    ElMessage.error('酒店名称不能为空')
    return
  }
  
  try {
    loading.value = true
    const res = await getHotelByName(hotelName)
    const result = res.data as any
    
    console.log('获取酒店详情响应:', result)
    
    // 检查返回的数据结构
    if (result && (result.code === 200 || result.code === 0)) {
      // 标准响应格式：{code: 200/0, data: {...}, msg: '...'}
      hotel.value = result.data || {}
    } else if (typeof result === 'object' && !Array.isArray(result) && result !== null) {
      // 直接返回对象格式
      hotel.value = result
    } else {
      console.error('获取酒店详情失败:', result)
      ElMessage.error(result?.msg || '获取酒店详情失败')
    }
  } catch (error) {
    console.error('获取酒店详情错误:', error)
    ElMessage.error('网络错误，获取酒店详情失败')
  } finally {
    loading.value = false
  }
}

// 获取酒店评价
const fetchHotelReviews = async () => {
  const hotelName = route.params.hotelName as string
  if (!hotelName) return
  
  try {
    reviewsLoading.value = true
    reviewsError.value = false
    const res = await getReviewsByHotel(hotelName)
    const result = res.data as any
    
    console.log('获取酒店评价响应:', result)
    
    // 检查返回的数据结构
    if (Array.isArray(result)) {
      // 直接返回数组格式
      reviews.value = result
    } else if (result && (result.code === 200 || result.code === 0)) {
      // 标准响应格式：{code: 200/0, data: [...], msg: '...'}
      reviews.value = Array.isArray(result.data) ? result.data : []
    } else {
      console.error('获取酒店评价失败:', result)
      reviewsError.value = true
    }
  } catch (error) {
    console.error('获取酒店评价错误:', error)
    reviewsError.value = true
  } finally {
    reviewsLoading.value = false
  }
}

// 获取酒店房间
const fetchRooms = async () => {
  const hotelName = route.params.hotelName as string
  if (!hotelName) return
  
  try {
    roomsLoading.value = true
    roomsError.value = false
    const res = await getRoomsByHotel(hotelName)
    const result = res.data as any
    
    console.log('获取酒店房间响应:', result)
    
    // 检查返回的数据结构
    if (Array.isArray(result)) {
      // 直接返回数组格式
      rooms.value = result
    } else if (result && (result.code === 200 || result.code === 0)) {
      // 标准响应格式：{code: 200/0, data: [...], msg: '...'}
      rooms.value = Array.isArray(result.data) ? result.data : []
    } else {
      console.error('获取酒店房间失败:', result)
      roomsError.value = true
    }
  } catch (error) {
    console.error('获取酒店房间错误:', error)
    roomsError.value = true
  } finally {
    roomsLoading.value = false
  }
}

// 创建订单
const createOrder = (room) => {
  // 跳转到创建订单页面，并传递酒店和房间信息
  router.push({
    path: '/create-order',
    query: {
      hotelName: hotel.value.hotelName,
      roomType: room.roomType
    }
  })
}

// 重试加载评论
const retryLoadReviews = () => {
  fetchHotelReviews()
}

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 返回上一页
const goBack = () => {
  router.back()
}

onMounted(() => {
  fetchHotelDetail()
  fetchHotelReviews()
  fetchRooms()
})
</script>

<style scoped>
.hotel-detail-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

.hotel-info-card, .hotel-map-card, .hotel-rooms-card, .hotel-reviews-card {
  margin-bottom: 30px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
}

.loading-container, .empty-container {
  min-height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.hotel-content {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.hotel-image {
  flex: 1;
  min-width: 300px;
  max-width: 500px;
  height: 300px;
}

.hotel-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}

.hotel-details {
  flex: 1;
  min-width: 300px;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.detail-item {
  display: flex;
  align-items: flex-start;
  gap: 10px;
}

.detail-item .el-icon {
  margin-top: 3px;
}

.map-container {
  height: 400px;
  border-radius: 8px;
  overflow: hidden;
}

/* 房间卡片样式 */
.room-card-col {
  margin-bottom: 20px;
}

.room-card {
  width: 100%;
  transition: transform 0.3s;
}

.room-card:hover {
  transform: translateY(-5px);
}

.room-layout {
  display: flex;
  gap: 20px;
}

.room-image {
  width: 200px;
  height: 150px;
  overflow: hidden;
  border-radius: 4px;
}

.room-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.room-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.room-type {
  margin: 0 0 10px 0;
  font-size: 18px;
  font-weight: 600;
}

.room-meta {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.room-price {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
}

.room-price span {
  font-size: 14px;
  font-weight: normal;
  color: #909399;
}

.room-available {
  font-size: 14px;
  color: #409EFF;
}

.room-features {
  margin-bottom: 15px;
}

.room-actions {
  margin-top: auto;
}

/* 评论样式 */
.reviews-list {
  margin-top: 20px;
}

.review-card {
  margin-bottom: 10px;
}

.review-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.user-id {
  font-weight: bold;
}

.review-content {
  white-space: pre-wrap;
  line-height: 1.5;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
}

@media (max-width: 768px) {
  .room-layout {
    flex-direction: column;
  }
  
  .room-image {
    width: 100%;
    height: 200px;
  }
}
</style> 